<template>
  <div class="page-header-index-wide">
    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a-select style="width: 140px" v-model="param.timeSlot" @change="timeSlotChange">
                <a-select-option value="week">最近七天</a-select-option>
                <a-select-option value="month">最近三十日</a-select-option>
                <a-select-option value="quarter">最近三个月</a-select-option>
                <a-select-option value="custom">自定义</a-select-option>
              </a-select>
            </div>
            <a-range-picker :style="{width: '256px'}"
                            @change="dateChange"
                            v-model="param.date"
                            format="YYYY-MM-DD"
                            :disabledDate="disabledDate"
            />
          </div>
          <a-tab-pane loading="true" tab="页面访问量" key="1">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="页面访问量" :dataSource="barData" yaxisText="访问次数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="页面访问量排行" :list="rankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>

          <a-tab-pane loading="true" tab="月份访问量" key="3">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="月份访问量" :dataSource="monthBarData" yaxisText="访问次数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="月份访问量排行" :list="monthRankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>

          <a-tab-pane loading="true" tab="模块访问量" key="2">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="模块访问量" :dataSource="moduleBarData" yaxisText="访问次数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="模块访问量排行" :list="moduleRankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>

          <a-tab-pane loading="true" tab="事件访问量" key="4">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="事件访问量" :dataSource="taskBarData" yaxisText="访问次数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="事件访问量排行" :list="taskRankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>


    </a-card>
    <br />
    <a-card>
      <!-- table区域-begin -->
      <div>

        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :loading="loading">

        <span slot="action" slot-scope="text, record">
          <a @click="goUserFlow(record.id)">查看该IP详细动作</a>
        </span>

        </a-table>
      </div>
    </a-card>

  </div>
  <!-- table区域-end -->
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { pageList, months } from '../../../utils/enum'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import moment from 'moment'
  import {getMonthDetailById,getPageNameById} from '../../../utils/enumFilter'


  function sortBy(attr, rev) {
    //第二个参数没有传递 默认升序排列
    if (rev == undefined) {
      rev = 1
    } else {
      rev = (rev) ? 1 : -1
    }
    return function(a, b) {
      a = a[attr]
      b = b[attr]
      if (a < b) {
        return rev * -1
      }
      if (a > b) {
        return rev * 1
      }
      return 0
    }
  }


  let that
  export default {
    name: 'Page',
    mixins: [JeecgListMixin],
    components: {
      RankList,
      Bar
    },
    data() {
      return {
        loading: false,
        monthList: months,
        pageList: pageList,
        description: 'CEO年历用户操作界面管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: 'ip',
            align: 'center',
            dataIndex: 'ip'
          },
          {
            title: '首页次数',
            align: 'center',
            dataIndex: 'index'
          },
          {
            title: '月份页次数',
            align: 'center',
            dataIndex: 'month'
          },
          {
            title: '事件页次数',
            align: 'center',
            dataIndex: 'task'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        dataSource: [],
        url: {
          list: '/statistics/countAllPageGroupByIp',
          delete: '/ceo/ceoPage/delete',
          deleteBatch: '/ceo/ceoPage/deleteBatch',
          exportXlsUrl: 'ceo/ceoPage/exportXls',
          importExcelUrl: 'ceo/ceoPage/importExcel'
        },
        param: {
          timeSlot: 'week',
          date: []
        },
        rankList: [],
        barData: [],
        monthRankList: [],
        monthBarData: [],
        moduleRankList: [],
        moduleBarData: [],

        taskRankList: [],
        taskBarData: [],
      }
    },
    created() {
      that = this

      that.initParam()
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      }
    },
    methods: {
      /**
       * 初始化相关参数
       */
      initParam() {

        //初始化时间设置
        that.setParamDate()
      },
      /**
       * 禁止选择的时间段
       */
      disabledDate(current) {
        return current < moment(that.$getDate({ date: new Date(2020, 0, 0) })).endOf('day') || current > moment().endOf('day')
      },
      /**
       * 新增用户数的时间段改变
       */
      timeSlotChange(e) {
        that.setParamDate(e)
      },
      dateChange(e) {
        that.param.timeSlot = 'custom'
        that.getDataSource()
      },
      setParamDate(key) {
        let times = 3600 * 24 * 1000 * 7
        switch (key) {
          case 'week':
            times = 3600 * 24 * 1000 * 7
            break
          case 'month':
            times = 3600 * 24 * 1000 * 30
            break
          case 'quarter':
            times = 3600 * 24 * 1000 * 90
            break
          case 'custom':
            return false
            break
          default:
            times = 3600 * 24 * 1000 * 7
            break
        }
        let data = that.$getDate({})
        let data1 = that.$getDate({ date: new Date(new Date().getTime() - times) })
        that.param.date = [moment(data1), moment(data)]
        that.getDataSource()
      },

      getDataSource() {
        that.loading = true
        let start = moment(that.param.date[0]).format('YYYY-MM-DD')
        let end = moment(that.param.date[1]).format('YYYY-MM-DD')
        that.getBarAndRank(start, end);
        that.getMonthAndTaskData(start,end);
        that.$Request({
          url: that.url.list,
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          that.dataSource = res.result
        }).catch(res => {
          if (!res) {
            res = '数据加载失败'
          }
          that.$message.warning(res)
        }).finally(() => {
          that.loading = false
        })
      },
      //每个IP访问量
      getBarAndRank(start, end) {
        that.loading = true
        that.$Request({
          url: '/statistics/pageCount',
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          let rankList = res.result.sort(sortBy('total', false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/page/g, 'name'))
          that.rankList = rankList;
          for (let item of rankList){
            item.name = getPageNameById(item.name);
          }
          let bar = []
          for (let item of res.result) {
            bar.push({
              x: getPageNameById(item.page),
              y: item.total
            })
          }
          that.barData = bar
        }).catch(res => {
          if (!res) {
            res = '数据加载失败'
          }
          that.$message.warning(res)
        }).finally(() => {
          that.loading = false
        })
      },

      //获取月份、模块和事件的访问量
      getMonthAndTaskData(start,end){
        that.loading = true
        //月份
        that.$Request({
          url: '/statistics/byMonth',
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          let rankList = res.result.sort(sortBy('total', false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/month/g, 'name'))
          for (let item of rankList){
              item.name = getMonthDetailById(item.name)
          }
          that.monthRankList = rankList
          let bar = []
          for(let i=1;i<=12;i++){
            let obj ={
              x: getMonthDetailById(i),
              y: 0
            }
            for (let item of res.result) {
              if(i == item.month){
                obj.y = item.total;
                break;
              }
            }
            bar.push(obj)
          }

          that.monthBarData = bar
        }).catch(res => {
          if (!res) {
            res = '数据加载失败'
          }
          that.$message.warning(res)
        }).finally(() => {
          that.loading = false
        })
        //模块
        that.$Request({
          url: '/statistics/byModule',
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          let rankList = res.result.sort(sortBy('total', false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/module/g, 'name'))

          that.moduleRankList = rankList
          let bar = []
          for (let item of res.result) {
            bar.push({
              x: item.module,
              y: item.total
            })
          }
          that.moduleBarData = bar
        }).catch(res => {
          if (!res) {
            res = '数据加载失败'
          }
          that.$message.warning(res)
        }).finally(() => {
          that.loading = false
        })
        //事件
        that.$Request({
          url: '/statistics/byChildModule',
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          let rankList = res.result.sort(sortBy('total', false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/child_module/g, 'name'))
          that.taskRankList = rankList
          let bar = []
          for (let item of res.result) {
            bar.push({
              x: item.child_module,
              y: item.total
            })
          }
          that.taskBarData = bar
        }).catch(res => {
          if (!res) {
            res = '数据加载失败'
          }
          that.$message.warning(res)
        }).finally(() => {
          that.loading = false
        })
      },
      goUserFlow(){
        that.$message.info("该功能待开发。。。")
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'

</style>
<style lang="scss" scoped>
  .circle-cust {
    position: relative;
    top: 28px;
    left: -100%;
  }

  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }

    p {
      line-height: 42px;
      margin: 0;

      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
</style>